import React, { useState } from 'react';
import { Upload, message, Image } from 'antd';
import { InboxOutlined } from '@ant-design/icons';
import type { UploadFile } from 'antd/es/upload/interface';
import styles from './index.module.less';

const { Dragger } = Upload;

interface AddPhotoProps {
  onImageSelect: (info: { fileList: UploadFile[]; hasImage: boolean }) => void;
}

const AddPhoto: React.FC<AddPhotoProps> = ({ onImageSelect }) => {
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as File);
    }
    setPreviewImage(file.url || (file.preview as string));
    setPreviewOpen(true);
  };

  const getBase64 = (file: File): Promise<string> =>
    new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result as string);
      reader.onerror = (error) => reject(error);
    });

  const handleChange = (info: any) => {
    const { file, fileList } = info;
    
    // 更新文件列表
    setFileList(fileList);
    
    // 通知父组件文件列表变化
    onImageSelect({
      fileList,
      hasImage: fileList.length > 0
    });

    // 处理上传状态
    if (file.status === 'uploading') {
      // message.loading(`${file.name} 正在上传...`);
    } else if (file.status === 'done') {
      message.success(`${file.name} 上传成功`);
    } else if (file.status === 'error') {
      message.error(`${file.name} 上传失败`);
    }
  };

  const customRequest = ({ onSuccess }: any) => {
    // 模拟上传成功
    setTimeout(() => {
      onSuccess('ok');
    }, 0);
  };

  return (
    <div className={styles.uploadContainer}>
      <Dragger
        name="file"
        multiple={false}
        accept=".jpg,.jpeg,.png"
        onChange={handleChange}
        onPreview={handlePreview}
        fileList={fileList}
        customRequest={customRequest}
        listType="picture-card"
        maxCount={1}
        showUploadList={{
          showPreviewIcon: true,
          showRemoveIcon: true,
          showDownloadIcon: false,
        }}
        beforeUpload={(file) => {
          const isImage = file.type.startsWith('image/');
          if (!isImage) {
            message.error('只能上传图片文件！');
            return Upload.LIST_IGNORE;
          }
          const isLt5M = file.size / 1024 / 1024 < 5;
          if (!isLt5M) {
            message.error('图片大小不能超过 5MB！');
            return Upload.LIST_IGNORE;
          }
          return true;
        }}
      >
        <p className={styles.uploadIcon}>
          <InboxOutlined />
        </p>
        <p className={styles.uploadText}>点击或拖拽文件到此区域上传</p>
        <p className={styles.uploadHint}>
          支持单个或批量上传，仅支持 jpg/png 格式
        </p>
      </Dragger>

      {previewOpen && (
        <Image
          style={{ display: 'none' }}
          preview={{
            visible: previewOpen,
            onVisibleChange: (visible) => setPreviewOpen(visible),
            src: previewImage,
            width: '100vw',
            height: '100vh',
            mask: false,
            scaleStep: 0.5,
            rootClassName: styles.previewRoot
          }}
        />
      )}
    </div>
  );
};

export default AddPhoto; 